﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsReadFile
{
    public partial class Form1 : Form
    {

        List<XimenziIndex> indexList = new List<XimenziIndex>();
       // List<XimenziIndex> indexList2;
        private string remotePath = ConfigurationManager.AppSettings["remotePath"];
        private string localPath = ConfigurationManager.AppSettings["localPath"];


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream(@"F:\__dhinf.000", FileMode.Open, FileAccess.Read);
           
            StreamReader sr = new StreamReader(fs);

           string content = sr.ReadToEnd();
            Console.WriteLine("streamRead=="+content);


            

            FileStream fsout = new FileStream(@"F:\__dhinf111.000", FileMode.OpenOrCreate, FileAccess.ReadWrite);

            StreamWriter srout = new StreamWriter(fsout);

            XimenziIndex x = new XimenziIndex();
           
          string test =  x.Construct();


            srout.Write(test);
            srout.Flush();
            srout.Close();

        }

        //测试操作共享文件
        private void button2_Click(object sender, EventArgs e)
        {


            using (SharedTool tool = new SharedTool("acer2", "123456eee", "127.0.0.1"))
            {
                string selectPath = @"\\127.0.0.1\th";

                var dicInfo = new DirectoryInfo(selectPath);//选择的目录信息  

                DirectoryInfo[] dic = dicInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly);
                foreach (DirectoryInfo temp in dic)
                {
                    Console.WriteLine(temp.FullName);
                }

                Console.WriteLine("---------------------------");
                FileInfo[] textFiles = dicInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);//获取所有目录包含子目录下的文件  
                foreach (FileInfo temp in textFiles)
                {
                  
                    Console.WriteLine(temp.Name);
                }

                //把共享文件下载到本地
                // FileStream fs = new FileStream(selectPath + textFiles[0].ToString(), FileMode.Open);
                if (!File.Exists(@"F:\6666.MPF"))
                {
                    File.Copy(@"\\127.0.0.1\th\6666.MPF", @"F:\6666.MPF");

                }
                else
                {
                    File.Delete(@"F:\6666.MPF");
                    File.Copy(@"\\127.0.0.1\th\6666.MPF", @"F:\6666.MPF");

                }
                // File.Copy(@"F:\6667.MPF", @"\\127.0.0.1\th\6668.MPF");

            }



        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //combobox加载
            DirectoryInfo dire = new DirectoryInfo(remotePath);
            DirectoryInfo[] dires = dire.GetDirectories();
            comboBox1.Items.AddRange(dires);
            comboBox1.Items.Add("");
            //获取机床端目录
            string user = ConfigurationManager.AppSettings["user"];
            string password = ConfigurationManager.AppSettings["password"];
            string ip = ConfigurationManager.AppSettings["ip"];
            try
            {
                using (SharedTool tool = new SharedTool(user, password, ip))
                {
                    string ss = ConfigurationManager.AppSettings["remotePath"];
                   // FileStream fs = new FileStream(ConfigurationManager.AppSettings["remotePath"]+ "__dhinf.000", FileMode.Open);
               // StreamReader sr = new StreamReader(fs);
                    using (StreamReader sr = new StreamReader(remotePath + "__dhinf.000", Encoding.Default))
                    {
                        string indexContent = sr.ReadToEnd();
                        string[] indexContentArray = indexContent.Split('\0');
                        indexContentArray = indexContentArray.Where(s => !string.IsNullOrEmpty(s)).ToArray();

                        for (int i = 0; i < indexContentArray.Length; i = i + 5)
                        {
                            XimenziIndex s1 = new XimenziIndex();
                            s1.Type = indexContentArray[i];
                            s1.FileName = indexContentArray[i + 1];
                            s1.ProgramName = indexContentArray[i + 2];
                            s1.NumberType = indexContentArray[i + 4];
                            indexList.Add(s1);
                        }







                        UpdateListBox();


                    }
                }
                
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex);
            }
           
        }
        //test
        private void button5_Click(object sender, EventArgs e)
        {
            XimenziIndex ximenziIndex = new XimenziIndex();
            ximenziIndex.Type = "MPF";
            ximenziIndex.FileName = "ABCD1234";
            ximenziIndex.ProgramName = "ABCD123456789";
            ximenziIndex.NumberType = "65775";


            FileStream fsRead = new FileStream(remotePath + "__dhinf.000", FileMode.Open,FileAccess.ReadWrite);
            StreamReader sr = new StreamReader(fsRead);
            string content = sr.ReadToEnd();
           sr.Close();
            fsRead.Close();
            //删除索引文件
            File.Delete(remotePath + "__dhinf.000");
            //创建新的索引文件

            FileStream fsWrite = new FileStream(remotePath + "__dhinf.000", FileMode.Create, FileAccess.ReadWrite);

            string ss = ximenziIndex.Construct();
            string newContent = content + ximenziIndex.Construct();
            StreamWriter sw = new StreamWriter(fsWrite);
            sw.Write(newContent);
            sw.Flush();
            sw.Close();
            fsWrite.Close();

        }
        /// <summary>
        /// 更新listbox,显示programname
        /// </summary>
        public void UpdateListBox()
        {
            listBox1.Items.Clear();
            listBox2.Items.Clear();
            listBox3.Items.Clear();

            //获取本地目录,list2显示
            string localPath = ConfigurationManager.AppSettings["localPath"];
            var dicInfo = new DirectoryInfo(localPath);//选择的目录信息  

            DirectoryInfo[] dic = dicInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly);
            foreach (var item in dic)
            {
                //string programName = GetProgramName(item.Name);
                listBox2.Items.Add(item.Name);

            }
            FileInfo[] textFiles = dicInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly);//获取所有目录包含子目录下的文件  
            foreach (var item in textFiles)
            {
                //string fileName = GetProgramName(item.Name);
                listBox2.Items.Add(item.Name);

            }
            //机床端界面显示，listbox1显示  和 机床端文件名listbox3显示
            string remotePath;
            if (comboBox1.SelectedItem == null)
            {
                remotePath = ConfigurationManager.AppSettings["remotePath"] ;

            }
            else
            {
                 remotePath = ConfigurationManager.AppSettings["remotePath"] + comboBox1.SelectedItem.ToString();

            }
            var dicInfo1 = new DirectoryInfo(remotePath);//选择的目录信息  

            DirectoryInfo[] dic1 = dicInfo1.GetDirectories("*.*", SearchOption.TopDirectoryOnly);
            foreach (var item in dic1)
            {
                string programName = GetProgramName(item.Name);
                listBox1.Items.Add(programName);
                listBox3.Items.Add(item.Name);
            }
            FileInfo[] textFiles1 = dicInfo1.GetFiles("*.*", SearchOption.TopDirectoryOnly);//获取所有目录包含子目录下的文件  

            foreach (var item in textFiles1)
            {
                string fileName = GetProgramName(item.Name);

                listBox1.Items.Add(fileName);
                listBox3.Items.Add(item.Name);

            }

        }

        public string GetProgramName(string fileName)
        {
            foreach (var item in indexList)
            {
                if (item.FileName.Equals(fileName.Substring(0, fileName.Length-4)))
                {
                    return item.ProgramName + fileName.Substring(fileName.Length-4);
                }
            }
            return "";
        }

        //程序上传
        private void button3_Click(object sender, EventArgs e)
        {
            string remotePath1 = null;
            string remotePath2 = null;
            if (comboBox1.SelectedItem == null)
            {
                remotePath2 = ConfigurationManager.AppSettings["remotePath"];
            }
            else
            {
                remotePath2 = ConfigurationManager.AppSettings["remotePath"] + comboBox1.SelectedItem.ToString() + "\\";
            }
            try
            {
                //从索引文件list中获取真实文件名
                foreach (var item in indexList)
                {
                    string selectString = listBox1.SelectedItem.ToString();
                    if (item.ProgramName.Equals(selectString.Substring(0, selectString.Length-4)))
                    {
                        remotePath1 = remotePath2 + item.FileName + selectString.Substring(selectString.Length - 4);

                    }
                }

                string localPath1 = localPath + listBox1.SelectedItem.ToString();

                if (!File.Exists(localPath1))
                {
                    File.Copy(remotePath1, localPath1);

                }
                UpdateListBox();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex);
            }
            
            
        }

        public string GetFileNameFromProgramName(string programName,string path)
        {
            if (programName.Length < 13)
            {
                return programName;
            }
            else
            {
              string name =  CreateFileName(programName, path);
                return name + programName.Substring(programName.Length-4);
            }
        }
        //生成一个机床内没有的文件名
        public string CreateFileName(string progeamName,string path)
        {
            string fileName = null;
            //判断机床内是否存在相同的文件名，有就换
            for (int i = 1; i < 8; i++)
            {
                for (int j = 0; j < 36; j++)
                {
                    fileName = RandCreateFileName(progeamName, j, i);
                    if (!IsExist(fileName,path))
                    {
                        return fileName;
                    }
                }
            }

            return "";

        }
        //判断是不是已经存在相同文件名
        public bool IsExist(string name,string path)
        {
            DirectoryInfo dire = new DirectoryInfo(path);
            FileInfo[] files = dire.GetFiles();
            foreach (var item in files)
            {
                if (name.Equals(item.Name.Substring(0,item.Name.Length-4)))
                {
                    return true;
                }
            }
            DirectoryInfo[] dires = dire.GetDirectories();
            foreach (var item in dires)
            {
                if (name.Equals(item.Name.Substring(0, item.Name.Length - 4)))
                {
                    return true;
                }
            }

            return false;
        }

        //生成一个文件名,不带后缀的
        public string RandCreateFileName(string programName,int ssNum,int bitNum)
        {
            string fileName = programName.Substring(0,8);
            fileName = fileName.Remove(bitNum, 1);
            fileName = fileName.Insert(bitNum, ss[ssNum]);

            return fileName;
        }

        string[] ss = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "R", "J", "K", "L", "M", "N", "O", "P", "Q", "I", "S", "T", "U", "V", "W", "X", "Y", "Z" };

        //程序推送
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                //判断索引里有没有这个程序
                if (IsExistFromIdex(listBox2.SelectedItem.ToString()))
                {
                    MessageBox.Show("已经存在相同程序！");
                    return;

                }
                //处理程序名称
                string remotePath2 = null;
                if (comboBox1.SelectedItem == null)
                {
                    remotePath2 = remotePath;
                }
                else
                {
                    remotePath2 = remotePath + comboBox1.SelectedItem.ToString() + "\\";
                }
                string fileName = GetFileNameFromProgramName(listBox2.SelectedItem.ToString(), remotePath2);
                string remotePath1 = remotePath2 + fileName; 


                string localPath1 = ConfigurationManager.AppSettings["localPath"] + listBox2.SelectedItem.ToString();

                if (!File.Exists(remotePath1))
                {
                    File.Copy(localPath1, remotePath1);
                    //索引中增加程序
                    XimenziIndex ximenziIndex = new XimenziIndex();
                    
                        ximenziIndex.Type = listBox2.SelectedItem.ToString().Substring(listBox2.SelectedItem.ToString().Length - 3);

                    
                    ximenziIndex.FileName = fileName.Substring(0, fileName.Length-4);
                    ximenziIndex.ProgramName = listBox2.SelectedItem.ToString().Substring(0, listBox2.SelectedItem.ToString().Length - 4);
                    if (ximenziIndex.Type.Equals("WPD"))
                    {
                        ximenziIndex.NumberType = "77777";
                    }
                    else
                    {
                        ximenziIndex.NumberType = "65775";
                    }


                    AddProgramToIndex(ximenziIndex, remotePath2,indexList);


                    MessageBox.Show("success!");

                }
                else
                {
                    MessageBox.Show("文件已经存在！");
                }

                UpdateListBox();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex);
            }
           
        }
        //索引list中增加程序,and 创建一个索引文件
        public void AddProgramToIndex(XimenziIndex ximenziIndex,string remotePath,List<XimenziIndex> list)
        {
            //先判断是否已经存在此程序
            if (list != null)
            {
                foreach (var item in list)
                {
                    if (item.ProgramName.Equals(ximenziIndex.ProgramName))
                    {
                        MessageBox.Show("已经存在相同的程序名！");
                        return;
                    }
                }
                indexList.Add(ximenziIndex);
            }
           
            //复制指定的索引文件
            // FileStream fsRead = new FileStream(remotePath + "__dhinf.000", FileMode.Open, FileAccess.ReadWrite);
            // StreamReader sr = new StreamReader(fsRead);
            string content;
            using (StreamReader sr = new StreamReader(remotePath + "__dhinf.000",Encoding.Default))
            {
                 content = sr.ReadToEnd();
               
            }
           
            //删除索引文件
            File.Delete(remotePath + "__dhinf.000");
            //创建新的索引文件

            using (StreamWriter sw = new StreamWriter(remotePath + "__dhinf.000"))
            {
                string ss = ximenziIndex.Construct();
                string newContent = content + ximenziIndex.Construct();
                sw.Write(newContent);
                sw.Flush();
            }

            
            
           
        }

        //判断索引中是否含有此程序
        public bool IsExistFromIdex(string program)
        {
            foreach (var item in indexList)
            {
                if (item.ProgramName.Equals(program.Substring(0, program.Length-4)))
                {
                    return true;
                }
                
            }

            return false;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            UpdateListBox();
        }

        //列出对应目录下的所有文件
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            try
            {
                string path = remotePath + comboBox1.SelectedItem.ToString()+ "\\";
                //解析索引文件
                indexList = new List<XimenziIndex>();

               // FileStream fs = new FileStream(path + "\\__dhinf.000", FileMode.Open);
               // StreamReader sr = new StreamReader(fs);
                using (StreamReader sr = new StreamReader(path + "__dhinf.000", Encoding.Default))
                {
                    string indexContent = sr.ReadToEnd();
                    string[] indexContentArray = indexContent.Split('\0');
                    string[] indexContentArray1 = indexContentArray.Where(s => !string.IsNullOrEmpty(s)).ToArray();
                    foreach (var item in indexContentArray1)
                    {
                        Console.WriteLine(item);
                    }

                    for (int i = 0; i < indexContentArray1.Length; i = i + 5)
                    {
                        XimenziIndex s1 = new XimenziIndex();
                        s1.Type = indexContentArray1[i];
                        s1.FileName = indexContentArray1[i + 1];
                        s1.ProgramName = indexContentArray1[i + 2];
                        s1.NumberType = indexContentArray1[i + 4];
                        indexList.Add(s1);
                    }
                    UpdateListBox();


                }



            }
            catch (Exception ex)
            {

                MessageBox.Show("索引文件有问题！");
                listBox1.Items.Clear();
                Console.WriteLine(ex);
               
            }
            
        }

        //获取文件夹
        private void button6_Click(object sender, EventArgs e)
        {
            
            string localPathDire = localPath + listBox1.SelectedItem.ToString()+ "\\";
            string realFileName= "";
            foreach (var item in indexList)
            {
                string temp = listBox1.SelectedItem.ToString();
                if (item.ProgramName.Equals(temp.Substring(0,temp.Length - 4)))
                {
                    realFileName = item.FileName;
                }
            }
            string remotePathDire = remotePath + realFileName+ ".WPD" + "\\";
            //先获取文件夹内的索引
            List<XimenziIndex> list = new List<XimenziIndex>();
            using (StreamReader sr = new StreamReader(remotePathDire + "__dhinf.000",Encoding.Default))
            {
                try
                {
                    string content = sr.ReadToEnd();
                    string[] contentSplit = content.Split('\0');
                    string[] content1 = contentSplit.Where(s => !string.IsNullOrEmpty(s)).ToArray();
                    for (int i = 0; i < content1.Length; i = i+5)
                    {
                        XimenziIndex ss = new XimenziIndex();

                        ss.Type = content1[i];
                        ss.FileName = content1[i+1];
                        ss.ProgramName = content1[i + 2];
                        ss.NumberType = content1[i + 4];

                        list.Add(ss);
                    }
                   
                }
                catch (Exception ex)
                {

                    Console.WriteLine(ex);
                    MessageBox.Show("索引文件解析出错！");
                    listBox1.Items.Clear();
                }
                
            }

            if (!Directory.Exists(localPathDire))//若目标文件夹不存在
            {
                string newPath;
               
                Directory.CreateDirectory(localPathDire);//创建目标文件夹
                DirectoryInfo direc = new DirectoryInfo(remotePathDire);                            
                FileInfo[] fileinfo = direc.GetFiles();//获取源文件夹中的所有文件路径
                foreach (var item1 in fileinfo)
                {
                    string fileName = item1.Name.Substring(0, item1.Name.Length - 4);
                    //根据文件名获取程序名
                    string programName = null;
                    foreach (var item in list)
                    {
                        if (fileName.Equals(item.FileName))
                        {
                            programName = item.ProgramName;
                            break;
                        }

                    }

                    newPath = localPathDire + programName + item1.Name.Substring( item1.Name.Length - 4);
                    if (!item1.Name.Equals("__dhinf.000"))
                    {
                        string realpath = remotePathDire + item1.Name;
                        File.Copy(realpath, newPath, true);
                    }
                    
                }
            }
            UpdateListBox();
        }

        //文件夹推送
        private void button7_Click(object sender, EventArgs e)
        {
            string localPathDire = localPath + listBox2.SelectedItem.ToString() + "\\";
            string remotePathDire = remotePath + listBox2.SelectedItem.ToString() + "\\";
            
            //判断是否存在相同的文件夹
            string direName = listBox2.SelectedItem.ToString().Substring(0, listBox2.SelectedItem.ToString().Length-4);
            foreach (var item in indexList)
            {

                if (direName.Equals(item.ProgramName))
                {
                    MessageBox.Show("存在相同的程序文件夹！");
                    return;
                }
            }
            //创建文件并修改索引文件，把对应文件夹中的程序复制过去并增加索引文件
            //处理程序名称
            string remotePath2 = null;
            if (comboBox1.SelectedItem == null)
            {
                remotePath2 = remotePathDire;
            }
            else
            {
                remotePath2 = remotePathDire + comboBox1.SelectedItem.ToString() + "\\";
            }
            string fileName = GetFileNameFromProgramName(listBox2.SelectedItem.ToString(), remotePath);
            string remotePath1 = remotePath + fileName + "\\";


            string localPath1 = ConfigurationManager.AppSettings["localPath"] + listBox2.SelectedItem.ToString();

            if (!Directory.Exists(remotePath1))
            {
                //复制文件夹并增加索引
               
                    string newPath;

                    Directory.CreateDirectory(remotePath1);//创建目标文件夹
                     //创建文件夹中的空索引文件
                   FileStream fileStream =  File.Create(remotePath1 + "__dhinf.000");
                fileStream.Close();
                 DirectoryInfo direc = new DirectoryInfo(localPathDire);
                    FileInfo[] fileinfo = direc.GetFiles();//获取源文件夹中的所有文件路径
                    foreach (var item1 in fileinfo)
                    {
                    //处理本file 复制到机床目录
                    string direfileName;
                    if (item1.Name.Length < 13)
                    {
                        direfileName = item1.Name;
                    }
                    else
                    {
                        string tempname = GetFileNameFromProgramName(item1.Name, remotePath1);
                        direfileName = tempname;
                    }
                    File.Copy(localPathDire + item1.Name, remotePath1 + direfileName);

                    XimenziIndex ximenziIndex1 = new XimenziIndex();
                    ximenziIndex1.Type = item1.Name.Substring(item1.Name.Length - 3);
                    ximenziIndex1.FileName = direfileName.Substring(0, direfileName.Length - 4);
                    ximenziIndex1.ProgramName = item1.Name.Substring(0, item1.Name.Length - 4);
                    if (ximenziIndex1.Type.Equals("WPD"))
                    {
                        ximenziIndex1.NumberType = "77777";
                    }
                    else
                    {
                        ximenziIndex1.NumberType = "65775";

                    }
                    AddProgramToIndex(ximenziIndex1, remotePath1,null);
                        
                    
                    }
                    
                
                //外部索引中增加程序
                XimenziIndex ximenziIndex = new XimenziIndex();

                ximenziIndex.Type = listBox2.SelectedItem.ToString().Substring(listBox2.SelectedItem.ToString().Length - 3);


                ximenziIndex.FileName = fileName.Substring(0, fileName.Length - 4);
                ximenziIndex.ProgramName = listBox2.SelectedItem.ToString().Substring(0, listBox2.SelectedItem.ToString().Length - 4);
                if (ximenziIndex.Type.Equals("WPD"))
                {
                    ximenziIndex.NumberType = "77777";
                }
                else
                {
                    ximenziIndex.NumberType = "65775";
                }


                AddProgramToIndex(ximenziIndex, remotePath,indexList);


                MessageBox.Show("success!");

            }
            else
            {
                MessageBox.Show("文件已经存在！");
            }

            UpdateListBox();

        }
    }
}
